package com.plian.system.controller.nkgl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.entity.nkgl.InternalManagement;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.nkgl.IInternalManagementService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.nkgl.InternalManagementVO;
import com.plian.system.wrapper.nkgl.InternalManagementWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 内控管理制度
 */
@Slf4j
@RestController
@RequestMapping("api/inernalManagement")
@AllArgsConstructor
public class InternalManagementController extends BaseController {

    private IInternalManagementService iInternalManagementService;

    private InternalManagementWrapper internalManagementWrapper;

    private FormWorkflowService formWorkflowService;

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("内控管理制度-提交")
    public R submit(@Valid @RequestBody InternalManagement internalManagement) {
        Boolean result = iInternalManagementService.submit(internalManagement);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(internalManagement.getId()),internalManagement.getFormType(),processVariable);

        return result ? R.data(internalManagement) : new R(CommonCode.FAIL);
    }
    /**
     * 新增或修改
     */
    @PostMapping("/edit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("内控管理制度-编辑")
    public R edit(@Valid @RequestBody InternalManagement internalManagement) {
        return iInternalManagementService.edit(internalManagement) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }
    /**
     * 删除
     */
    @PostMapping("/remove")
    @LogOperation("内控管理制度-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
        return iInternalManagementService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<InternalManagementVO> detail(@Valid @RequestBody InternalManagement internalManagement) {
        InternalManagement detail = iInternalManagementService.getOne(Condition.getQueryWrapper(internalManagement));
        return R.data(internalManagementWrapper.entityToVO(detail));
    }

    /**
     * 分页
     */
    @PostMapping("/list")
    public ListResult<InternalManagementVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        String yearValue="";
        if(entityList!=null&&entityList.size()>0){
            for (int i=0;i<entityList.size();i++) {
                SearchEntity entity= entityList.get(i);
                if(entity!=null&&entity.getField()!=null){
                    String field=entity.getField();
                    if(field.equals("year")){
                        String value=String.valueOf(entity.getValue());
                        if(yearValue!=null){
                            yearValue=value;
                        }
                        entityList.remove(i);
                    }
                }
            }
        }
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }

        QueryWrapper<InternalManagement> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new InternalManagement()), entityList
        );
        TokenSearch<InternalManagement> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);
        if(yearValue!=null&&!yearValue.equals("")){
            Integer year=Integer.valueOf(yearValue);
            LocalDateTime first= firstTimeOfYear(year-1).plusYears(1).minusSeconds(1);
            LocalDateTime end= firstTimeOfYear(year).plusYears(1).minusSeconds(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            queryWrapper.lambda().between(InternalManagement::getUpdateTime, first.format(formatter),end.format(formatter));
        }

        IPage<InternalManagement> pages = iInternalManagementService.page(Condition.getPage(query), queryWrapper);
        List<InternalManagementVO> internalManagementVOList = internalManagementWrapper.entityToVO(pages.getRecords());
        ListResult<InternalManagementVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(internalManagementVOList);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }
    public static LocalDateTime firstTimeOfYear(int year) {
        return LocalDateTime.of(LocalDate.ofYearDay(year, 1), LocalTime.MIN);
    }
}
